/**
 * Copyright (c) 2018-2028, Joffee.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sailmi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import javax.validation.Valid;

import com.sailmi.common.controller.BaseController;
import com.sailmi.common.constant.AppConstant;
import com.sailmi.common.model.auth.AuthInfo;
import com.sailmi.common.mybatis.support.Condition;
import com.sailmi.common.mybatis.support.Query;
import com.sailmi.common.tool.api.R;
import com.sailmi.common.tool.utils.Func;
import com.sailmi.common.tool.utils.SecureUtil;
import com.sailmi.system.entity.Enterprise;
import com.sailmi.system.entity.User;
import com.sailmi.system.entity.UserEnterprise;
import com.sailmi.system.service.IRoleService;
import com.sailmi.system.service.IUserEnterpriseService;
import com.sailmi.system.service.IUserService;
import com.sailmi.system.vo.EnterpriseAdminInfoVo;
import com.sailmi.system.vo.EnterpriseVO;
import com.sailmi.system.service.IEnterpriseService;
import com.sailmi.system.wrapper.EnterpriseWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;
import java.util.Objects;

/**
 *  控制器
 *
 * @author sailmi
 * @since 2020-09-02
 */
@RestController
@RequestMapping("/enterprise")
@Tag(name = "", description = "接口")
public class EnterpriseController extends BaseController {
	@Resource
	private IEnterpriseService enterpriseService;
	@Resource
	private IUserService userService;
	@Resource
	private IRoleService roleService;
	@Resource
	private IUserEnterpriseService userEnterpriseService;
	/**
	* 详情
	*/
	@GetMapping("/detail")
	@Operation(summary = "详情", description = "传入enterprise")
	public R<EnterpriseVO> detail(@ModelAttribute Enterprise enterprise) {
		Enterprise detail = enterpriseService.getOne(Condition.getQueryWrapper(enterprise));
		return R.data(EnterpriseWrapper.build().entityVO(detail));
	}


	/**
	 * 获取企业分配的服务包的分配树形结构
	 */
	@GetMapping("/enterprise-tree-keys")
	@Operation(summary = "角色所分配的树", description = "角色所分配的树")
	public R<List<String>> enterpriseServiceTreeKeys(@RequestParam(name="enterpriseId") String enterpriseId) {
		return R.data(enterpriseService.enterpriseServiceTreeKeys(enterpriseId));
	}



	/**
	 * 设置企业服务包
	 *
	 * @param enterpriseId
	 * @param serviceIds
	 * @RequestBody(required=false) AuthUser user
	 * @return
	 */
	@PostMapping("/serviceGrant")
	@Operation(summary = "服务包菜单设置", description = "传入enterpriseId和serviceIds")
	public R grantService(@Parameter(name = "企业ID", required = true) @RequestParam(name="enterpriseId") String enterpriseId,
						  @Parameter(name = "serviceId集合", required = true) @RequestParam(name="serviceIds") String serviceIds,
						  HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();

		boolean temp = enterpriseService.grantServices(enterpriseId, Func.toLongList(serviceIds),authInfo.getAuthUser());
		return R.status(temp);
	}
	/**
	 * 设置企业服务包
	 *
	 * @param enterpriseId
	 * @param serviceIds
	 * @RequestBody(required=false) AuthUser user
	 * @return
	 */
	@PostMapping("/serviceReject")
	@Operation(summary = "服务包菜单设置", description = "传入enterpriseId和serviceIds")
	public R rejectService(@Parameter(name = "企业ID", required = true) @RequestParam(name="enterpriseId") String enterpriseId,
						  @Parameter(name = "serviceId集合", required = true) @RequestParam(name="serviceIds") String serviceIds,
						  HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();

		boolean temp = enterpriseService.rejectServices(enterpriseId, Func.toLongList(serviceIds),authInfo.getAuthUser());
		return R.status(temp);
	}
	/**
	* 分页
	*/
	@GetMapping("/list")
	@Operation(summary = "分页", description = "传入enterprise")
	public R<IPage<EnterpriseVO>> list(@ModelAttribute Enterprise enterprise,@ModelAttribute Query query,HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();

		QueryWrapper<Enterprise> queryWrapper = Condition.getQueryWrapper(enterprise);
		if(authInfo!=null && authInfo.getTenantId()!=null){
			if(authInfo.getTenantId().equals("000000")) {//平台管理员

			}else{
				queryWrapper.eq("tenant_id", authInfo.getTenantId());
			}
		}
		IPage<Enterprise> pages = enterpriseService.page(Condition.getPage(query), queryWrapper);
		return R.data(EnterpriseWrapper.build().pageVO(pages));
	}


	@GetMapping("/enterpriselist")
	@Operation(summary = "分页", description = "传入enterprise")
	public R<List<Enterprise>> list() {
		QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
		enterpriseQueryWrapper.eq("tenant_id","000000");
		List<Enterprise> enterLists = enterpriseService.list(enterpriseQueryWrapper);
		return R.data(enterLists);
	}
	/**
	* 自定义分页
	*/
	@GetMapping("/page")
	@Operation(summary = "分页", description = "传入enterprise")
	public R<IPage<EnterpriseVO>> page(@ModelAttribute EnterpriseVO enterprise,@ModelAttribute Query query) {
		IPage<EnterpriseVO> pages = enterpriseService.selectEnterprisePage(Condition.getPage(query), enterprise);
		return R.data(pages);
	}

	/**
	* 新增
	*/
	@PostMapping("/save")
	@Operation(summary = "新增", description = "传入enterprise")
	public R save(@Valid @RequestBody Enterprise enterprise) {
		if(enterprise!=null){
			if(StringUtils.isEmpty(enterprise.getTenantId())){
				enterprise.setTenantId("000000");
			}
		}
		return R.status(enterpriseService.save(enterprise));
	}

	/**
	* 修改
	*/
	@PostMapping("/update")
	@Operation(summary = "修改", description = "传入enterprise")
	public R update(@Valid @RequestBody Enterprise enterprise) {
		if(enterprise!=null){
			if(StringUtils.isEmpty(enterprise.getTenantId())){
				enterprise.setTenantId("000000");
			}
		}
		return R.status(enterpriseService.updateById(enterprise));
	}

	/**
	* 新增或修改
	*/
	@PostMapping("/submit")
	@Operation(summary = "新增或修改", description = "传入enterprise")
	public R submit(@Valid @RequestBody Enterprise enterprise) {
		if(enterprise!=null){
			if(StringUtils.isEmpty(enterprise.getTenantId())){
				enterprise.setTenantId("000000");
			}
		}
		return R.status(enterpriseService.saveOrUpdate(enterprise));
	}


	/**
	* 删除
	*/
	@PostMapping("/remove")
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam(name="ids") String ids) {
		return R.status(enterpriseService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 下拉数据源
	 */
	@Operation(summary = "企业下拉数据源", description = "传入企业")
	@GetMapping("/select")
	public R<List<Enterprise>> select(@ModelAttribute Enterprise enterprise) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		QueryWrapper<Enterprise> queryWrapper = Condition.getQueryWrapper(enterprise);
		List<Enterprise> list = enterpriseService.list((!authInfo.getTenantId().equals(AppConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Enterprise::getTenantId, authInfo.getTenantId()) : queryWrapper);
		return R.data(list);
	}

	/**
	 * 删除
	 */
	@PostMapping("/initAdmin")
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R initAdmin(@RequestBody EnterpriseAdminInfoVo enterpriseAdminInfoVo) {
		//创建管理用户
		System.out.println("Now Init Admin!");
		User adminUser=new User();
		adminUser.setAccount(enterpriseAdminInfoVo.getAdminAccount());
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(adminUser);
		adminUser = userService.getOne(queryWrapper);
		if(Objects.nonNull(adminUser)){
			return R.fail("用户名已存在！");
		}
		//执行后续插入操作
		adminUser=new User();
		adminUser.setAccount(enterpriseAdminInfoVo.getAdminAccount());
		adminUser.setPassword(enterpriseAdminInfoVo.getAdminPass());
		adminUser.setDefaultEnterpriseId(enterpriseAdminInfoVo.getEnterpriseId());
		System.out.println("Now Init Admin Save User!");
		userService.save(adminUser);
		UserEnterprise userEnterprise = new UserEnterprise();
		userEnterprise.setEnterpriseId(enterpriseAdminInfoVo.getEnterpriseId());
		userEnterprise.setCreateUser(0l);
		userEnterprise.setStatus(1);
		userEnterprise.setUserId(adminUser.getId());
		System.out.println("Now Init Admin Save Enterprise!");
		userEnterpriseService.save(userEnterprise);
		//为用户授权
		System.out.println("Now Init Admin Auth User!");
		return R.status(userService.grant(String.valueOf(adminUser.getId()),"-2,-1,0"));
	}
}
